/**
 * 表单工具类
 *
 * */
import {clearStorage, getStorage, getStorageNoTime, saveStorageNoTime} from "./StorageUtils";
import {Modal} from "antd";
import React from "react";
import { ExclamationCircleOutlined } from '@ant-design/icons';
import {getUserId} from "./Utils";

/**
 * 获取表单存储【LocalStore】key
 * @param classObj
 * @returns {string}
 */
export function formDataStoreKey(classObj){
  try {
    return getUserId()+"_"+classObj._reactInternalFiber.type.name + '_'+ 'formData';
  } catch (e) {
    console.error(e);
  }
}

/**
 * 清理表单缓存
 * @param self
 */
export function clearCacheFormData(self){
  clearStorage(formDataStoreKey(self), true);
}

/**
 * 缓存表单数据
 * React、Antd-4.3
 * @date 2020-9-16 16:45:20
 * @author wanJie.Peng
 */
export function cacheFormData(self, getFormDataName="validateFormFields"){
  let fn = async ()=>{
    console.debug("准备缓存："+getFormDataName)
    if(
      self[getFormDataName]
      && (
        self[getFormDataName].constructor.name === "AsyncFunction" || self[getFormDataName].constructor.name === "Function"
      )
    ){
      let formKey = formDataStoreKey(self);
      let data = await self[getFormDataName](false);
      console.debug("开始缓存====="+formKey)
      saveStorageNoTime(formDataStoreKey(self), data);
    }
  }
  fn();
}


/**
 * 加载表单的缓存数据
 * @param self
 * @param isRemind 是否提示
 */
export function loadCacheFormData(self, isRemind=true){
  let formData = getStorageNoTime(formDataStoreKey(self));
  let fn = ()=>{
    if( self.setFormData && self.setFormData.constructor.name === "Function"){
      self.setFormData(formData);
    }
  }
  if( formData ){
    if( isRemind ){
      Modal.confirm({
        title: '检测到您有未提交的表单数据，是否要恢复?',
        icon: <ExclamationCircleOutlined />,
        content: '',
        okText: '恢复',
        cancelText: '不了，谢谢。',
        onOk() {
          fn();
        }
      });
    }else {
      fn();
    }

  }

}

/**
 * 服务接口返回数据后加载表单的缓存数据
 * @param self
 * @param isRemind
 */
export function serverLoadCacheFormData(self, data={}, isRemind=true){

  let setFn = (tempDta = {})=>{
    if( self.setFormData && self.setFormData.constructor.name === "Function"){
      self.setFormData(tempDta);
    }
  }

  // 从服务器拉取数据后默认赋值
  setFn( data );

  let formData = getStorageNoTime(formDataStoreKey(self));

  if( formData ){
    // 服务器返回的数据和新的合在一起
    let newData = {...data, ...formData};
    if( isRemind ){
      Modal.confirm({
        title: '检测到您有未提交的表单数据，是否要恢复?',
        icon: <ExclamationCircleOutlined />,
        content: '',
        okText: '恢复',
        cancelText: '不了，谢谢。',
        onOk() {
          setFn(newData);
        }
      });
    }else {
      setFn(newData);
    }

  }

}

// 验证文件上传
export function validatorByFileUpload(refName, msg, self){
  msg = '请选择'+msg;
  return [
    {
      required: true,
      validator:  async (rule, value) => {
        let dataArray = self[refName].getFileList();
        if( !dataArray || dataArray.length === 0 ){
          return Promise.reject(msg);
        }
        return Promise.resolve();

      }
    },
  ]
}

// 验证通过 getData
export function validatorByGetData(refName, msg, self, dataIsObj ){
  msg = msg+'不能为空';
  return [
    {
      required: true,
      validator:  async (rule, value) => {
        let data = self[refName].getData();
        if( dataIsObj === true ){
          if( !data || Object.keys(data).length === 0 ){
            return Promise.reject(msg);
          }
        }else {
          if( !data ){
            return Promise.reject(msg);
          }
        }
        return Promise.resolve();

      }
    },
  ]
}

// 验证地区选择
export function validatorByAreaSelect(refName, msg, self){
  msg = '请选择'+msg;
  return [
    {
      required: true,
      validator:  async (rule, value) => {
        let data = self[refName].getData();
        if( !data || Object.keys(data).length === 0 ){
          return Promise.reject(msg);
        }
        return Promise.resolve();

      }
    },
  ]
}

// 验证地址
export function validatorByAddress(refName, msg, self){
  msg = '请选择'+msg;
  return [
    {
      required: true,
      validator:  async (rule, value) => {
        let data = self[refName].getData();
        if( !data || Object.keys(data).length === 0 ){
          return Promise.reject(msg);
        }
        if( !data.provinceCode ){
          return Promise.reject('省不能为空');
        }
        if( !data.cityCode ){
          return Promise.reject('市不能为空');
        }
        if( !data.address ){
          return Promise.reject('详细地址不能为空');
        }
        return Promise.resolve();

      }
    },
  ]
}

// 验证地址
export function validatorByAreaCascader(refName, msg, self){
  msg = '请选择'+msg;
  return [
    {
      required: true,
      validator:  async (rule, value) => {
        let data = self[refName]._getAreaData();
        if( !data || Object.keys(data).length === 0 ){
          return Promise.reject(msg);
        }
        if( !data.provinceCode ){
          return Promise.reject('省不能为空');
        }
        if( !data.cityCode ){
          return Promise.reject('市不能为空');
        }

        return Promise.resolve();

      }
    },
  ]
}


// 验证通过选择人员
export function validatorByMemberSelect(memberSelectKey, msg, self){
  msg = '请选择'+msg;
  return [
    {
      required: true,
      validator:  async (rule, value) => {
        let userSelect = self[memberSelectKey];

        if( userSelect.props.sysuser ){
          let dataArray = await self[memberSelectKey].getData();
          if( !dataArray || dataArray.length === 0 ){
            return Promise.reject(msg);
          }
          return Promise.resolve();
        }else {
          let dataArray = self[memberSelectKey]._getDingUserData();
          if( !dataArray || dataArray.length === 0 ){
            return Promise.reject(msg);
          }
          return Promise.resolve();
        }

      }
    },
  ]
}

// 验证通过 FileUpload
export function validatorFileUploadData(self, refName, msg, fnName){
  return [
    {
      required: true,
      validator:  async () => {
        let thisArg = self[refName];
        if (thisArg) {
          let data = thisArg[fnName].call(thisArg)
          if (!data.addFileList || data.addFileList.length <= 0) {
            return Promise.reject(msg)
          }
        }
      }
    },
  ]
}
